// import { printLabelRecord } from '@/api/wipManagement/productionCenter/labelsPrinting';

function standardFormat(data) {
  return ['', null, undefined].includes(data?.materialLength)
    || ['', null, undefined].includes(data?.materialWidth)
    ? '-'
    : `${data?.materialLength}*${data?.materialWidth}${
        ['', null, undefined].includes(data?.materialHeight)
          ? ''
          : `*${data?.materialHeight}`
      }${data?.materialUnitName}`
}

function getPaperboardStandards(orderQueryVo) {
  const { paperboardLength = '', paperboardWidth = '' } = orderQueryVo

  if (
    paperboardLength !== ''
    && paperboardLength !== null
    && paperboardWidth !== ''
    && paperboardWidth !== null
  )
    return `${paperboardWidth}*${paperboardLength}${orderQueryVo?.materialUnitName}`

  return '-'
}

const printDataList: any = []

let isPrinting = false

/**
 *
 * @param printingTemplate 标签打印模版dom实例对象
 * @param data 打印参数
 * @param resolveFn 成功回调
 * @param rejectFn 失败回调
 */

export function emitPrintFn(printingTemplate, data = {
  materialStandards: '-',
  materialLength: '-',
  materialWidth: '-',
  materialHeight: '-',
  materialUnitName: '-',
  shiftName: '-',
  workers: '-',
  remarks: '-',
  remark: '-',
  customerDeliveryDate: '',
  paperboardStandards: '',
}, resolveFn: any = null, rejectFn: any = null) {
  // 格式化数据
  data = {
    ...data,
    materialStandards: standardFormat(data),
    paperboardStandards: getPaperboardStandards(data),
    remarks: data.remarks || data.remark,
    customerDeliveryDate: data.customerDeliveryDate || '2099-12-31 23:59:59',
  }
  if (isPrinting) {
    printDataList.push({ data, resolveFn, rejectFn })

    return
  }

  const printData = {
    customShort: '',
    materialName: '',
    productionStandards: '',
    totalOrders: '',
    trayNum: '',
    planNum: '',
    productTime: '',
    trayCode: '',
  }

  for (const key in data)
    printData[key] = data[key]

  try {
    isPrinting = true
    printingTemplate?.printFn(printData).then((printSuccess) => {
      resolveFn(printSuccess)

      isPrinting = false

      if (printDataList && printDataList.length) {
        const {
          data: pData = {},
          resolveFn: pResolveFn = null,
          rejectFn: pRejectFn = null,
        } = printDataList[0]

        emitPrintFn(printingTemplate, pData, pResolveFn, pRejectFn)

        printDataList.shift()
      }
    })
  }
  catch (e) {
    console.log(e)

    rejectFn && rejectFn(e)
  }
}
